/**
 * 触摸反馈 Composable
 * 为移动设备提供触摸反馈效果
 */

import { ref, onMounted, onUnmounted } from 'vue'
import { isTouchDevice, isMobileDevice } from '../utils/deviceDetection.js'

/**
 * 触摸反馈 hook
 * @param {Object} options 配置选项
 * @returns {Object} 触摸反馈相关的方法和状态
 */
export function useTouchFeedback(options = {}) {
  const {
    hapticFeedback = true,
    visualFeedback = true,
    audioFeedback = false,
    feedbackDuration = 150,
    feedbackIntensity = 'medium'
  } = options

  const isTouch = ref(isTouchDevice())
  const isMobile = ref(isMobileDevice())
  const activeTouches = ref(new Set())

  /**
   * 触发触觉反馈
   * @param {string} type 反馈类型：'light', 'medium', 'heavy'
   */
  const triggerHapticFeedback = (type = feedbackIntensity) => {
    if (!hapticFeedback || !isTouch.value) return

    try {
      // 使用 Vibration API
      if (navigator.vibrate) {
        const patterns = {
          light: [10],
          medium: [20],
          heavy: [30]
        }
        navigator.vibrate(patterns[type] || patterns.medium)
      }

      // 使用 Haptic Feedback API (如果支持)
      if (window.DeviceMotionEvent && typeof DeviceMotionEvent.requestPermission === 'function') {
        // iOS 设备的触觉反馈
        const intensities = {
          light: 0.3,
          medium: 0.6,
          heavy: 1.0
        }
        
        // 注意：这需要用户手势触发
        if (window.navigator && window.navigator.vibrate) {
          const duration = Math.floor((intensities[type] || intensities.medium) * 50)
          window.navigator.vibrate(duration)
        }
      }
    } catch (error) {
      console.warn('Haptic feedback not supported:', error)
    }
  }

  /**
   * 触发视觉反馈
   * @param {HTMLElement} element 目标元素
   * @param {string} type 反馈类型
   */
  const triggerVisualFeedback = (element, type = 'tap') => {
    if (!visualFeedback || !element) return

    const feedbackClass = `touch-feedback-${type}`
    
    // 添加反馈类
    element.classList.add(feedbackClass)
    
    // 移除反馈类
    setTimeout(() => {
      element.classList.remove(feedbackClass)
    }, feedbackDuration)
  }

  /**
   * 触发音频反馈
   * @param {string} type 反馈类型
   */
  const triggerAudioFeedback = (type = 'tap') => {
    if (!audioFeedback) return

    try {
      // 创建简单的音频反馈
      const audioContext = new (window.AudioContext || window.webkitAudioContext)()
      const oscillator = audioContext.createOscillator()
      const gainNode = audioContext.createGain()

      oscillator.connect(gainNode)
      gainNode.connect(audioContext.destination)

      const frequencies = {
        tap: 800,
        success: 1000,
        error: 400
      }

      oscillator.frequency.setValueAtTime(frequencies[type] || frequencies.tap, audioContext.currentTime)
      oscillator.type = 'sine'
      
      gainNode.gain.setValueAtTime(0.1, audioContext.currentTime)
      gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.1)

      oscillator.start(audioContext.currentTime)
      oscillator.stop(audioContext.currentTime + 0.1)
    } catch (error) {
      console.warn('Audio feedback not supported:', error)
    }
  }

  /**
   * 处理触摸开始事件
   * @param {TouchEvent} event 触摸事件
   */
  const handleTouchStart = (event) => {
    if (!isTouch.value) return

    const touch = event.touches[0]
    const element = event.currentTarget
    const touchId = touch.identifier

    activeTouches.value.add(touchId)

    // 触发反馈
    triggerHapticFeedback('light')
    triggerVisualFeedback(element, 'press')
    
    // 添加按压状态
    element.classList.add('touch-active')
  }

  /**
   * 处理触摸结束事件
   * @param {TouchEvent} event 触摸事件
   */
  const handleTouchEnd = (event) => {
    if (!isTouch.value) return

    const element = event.currentTarget
    
    // 清除所有触摸
    activeTouches.value.clear()
    
    // 移除按压状态
    element.classList.remove('touch-active')
    
    // 触发释放反馈
    triggerVisualFeedback(element, 'release')
  }

  /**
   * 处理触摸取消事件
   * @param {TouchEvent} event 触摸事件
   */
  const handleTouchCancel = (event) => {
    handleTouchEnd(event)
  }

  /**
   * 为元素添加触摸反馈
   * @param {HTMLElement} element 目标元素
   * @param {Object} customOptions 自定义选项
   */
  const addTouchFeedback = (element, customOptions = {}) => {
    if (!element || !isTouch.value) return

    const options = { ...{ hapticFeedback, visualFeedback, audioFeedback }, ...customOptions }

    const touchStartHandler = (event) => {
      handleTouchStart(event)
      if (options.hapticFeedback) triggerHapticFeedback('light')
      if (options.audioFeedback) triggerAudioFeedback('tap')
    }

    const touchEndHandler = (event) => {
      handleTouchEnd(event)
      if (options.hapticFeedback) triggerHapticFeedback('medium')
    }

    element.addEventListener('touchstart', touchStartHandler, { passive: true })
    element.addEventListener('touchend', touchEndHandler, { passive: true })
    element.addEventListener('touchcancel', handleTouchCancel, { passive: true })

    // 返回清理函数
    return () => {
      element.removeEventListener('touchstart', touchStartHandler)
      element.removeEventListener('touchend', touchEndHandler)
      element.removeEventListener('touchcancel', handleTouchCancel)
    }
  }

  /**
   * 为按钮添加触摸反馈
   * @param {HTMLElement} button 按钮元素
   */
  const addButtonTouchFeedback = (button) => {
    return addTouchFeedback(button, {
      hapticFeedback: true,
      visualFeedback: true,
      audioFeedback: false
    })
  }

  /**
   * 为链接添加触摸反馈
   * @param {HTMLElement} link 链接元素
   */
  const addLinkTouchFeedback = (link) => {
    return addTouchFeedback(link, {
      hapticFeedback: true,
      visualFeedback: true,
      audioFeedback: false
    })
  }

  /**
   * 批量添加触摸反馈
   * @param {string} selector CSS 选择器
   * @param {Object} customOptions 自定义选项
   */
  const addTouchFeedbackToElements = (selector, customOptions = {}) => {
    if (!isTouch.value) return []

    const elements = document.querySelectorAll(selector)
    const cleanupFunctions = []

    elements.forEach(element => {
      const cleanup = addTouchFeedback(element, customOptions)
      if (cleanup) cleanupFunctions.push(cleanup)
    })

    return cleanupFunctions
  }

  // 自动为常见的交互元素添加触摸反馈
  let cleanupFunctions = []

  onMounted(() => {
    if (isTouch.value) {
      // 为按钮添加触摸反馈
      cleanupFunctions.push(...addTouchFeedbackToElements('button, .btn, [role="button"]'))
      
      // 为链接添加触摸反馈
      cleanupFunctions.push(...addTouchFeedbackToElements('a[href], .link'))
      
      // 为可点击元素添加触摸反馈
      cleanupFunctions.push(...addTouchFeedbackToElements('[onclick], .clickable, .qq-group'))
    }
  })

  onUnmounted(() => {
    // 清理所有事件监听器
    cleanupFunctions.forEach(cleanup => cleanup())
    cleanupFunctions = []
  })

  return {
    isTouch,
    isMobile,
    activeTouches,
    triggerHapticFeedback,
    triggerVisualFeedback,
    triggerAudioFeedback,
    addTouchFeedback,
    addButtonTouchFeedback,
    addLinkTouchFeedback,
    addTouchFeedbackToElements
  }
}